package com.ganzalang.gmall.learning.netty.nio;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;

/**
 * @description: 向文件写数据
 * @author: Ganzalang
 * @Date 2021/7/12 20:54
 */
public class NIOFileChannel01 {

    public static void main(String[] args) throws IOException {


        // 数据流向：data-》Buffer-》Channel-》文件
        String data = "hello, 尚硅谷";
        // 创建一个缓冲区
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        // 向Buffer写数据
        byteBuffer.put(data.getBytes());
        // 对缓冲区进行flip
        byteBuffer.flip();

        FileOutputStream fileInputStream = new FileOutputStream("D:\\file01.txt");
        // FileChannel的实现是FileChannelImpl
        FileChannel fileChannel = fileInputStream.getChannel();
        // 将缓冲区数据写入Channel
        fileChannel.write(byteBuffer);
        fileInputStream.close();
    }
}
